import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'common',
    component: () => import('@/Common.vue'),
    children: [ //嵌套子路由
      {
        path: '',
        component: () => import('../views/HomeView.vue')
      },
      {
        path: 'about',
        component: () => import('../views/AboutView.vue')
      }
      ,
      {
        path: 'Administrative',
        component: () => import('@/views/AdministrativeView.vue')
      }
      ,
      {
        path: 'Announcement',
        component: () => import('@/views/AnnouncementView.vue')
      }
      ,
      {
        path: 'Scheduling',
        component: () => import('@/views/SchedulingView.vue')
      },
      {
        path: 'Appointment',
        component: () => import('@/views/AppointmentView.vue')
      }
      ,
      {
        path: 'Patient',
        component: () => import('@/views/PatientView.vue')
      }
      ,
      {
        path: 'PatientAttendance',
        component: () => import('@/views/PatientAttendanceView.vue')
      }
      ,
      {
        path: 'Hospital',
        component: () => import('@/views/HospitalView.vue')
      }
      ,
      {
        path: 'Admin',
        component: () => import('@/views/AdminView.vue')
      },
      {
        path: 'Doctor',
        component: () => import('@/views/DoctorView.vue')
      },
      {
        path: 'User',
        component: () => import('@/views/UserView.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/registerView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/register') {
    // 如果要前往的路径是登录页面或注册页面，则直接放行
    next();
  } else {
    // 否则检查用户是否已登录
    const user = localStorage.getItem("user");
    if (!user) {
      // 如果未登录，则重定向到登录页面
      next("/login");
    } else {
      // 如果已登录，则放行
      next();
    }
  }
})
export default router
